package com.ideaaedi.zoo.example.springboot.websocket.callback;

import com.alibaba.fastjson2.JSON;
import com.ideaaedi.commonds.time.DateTimeConverter;
import com.ideaaedi.zoo.diy.artifact.websocket.core.AbstractWebSocketEndpoint;
import com.ideaaedi.zoo.diy.artifact.websocket.core.WebSocketCallback;
import com.ideaaedi.zoo.example.springboot.websocket.util.WebSocketUidUtil;
import jakarta.annotation.Resource;
import jakarta.websocket.Session;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.MDC;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 回调分布式统一管理会话id
 */
@Slf4j
@Component
@EnableScheduling // 确保启用了@Scheduled
public class DemoWebSocketCallback implements WebSocketCallback {
    
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    
    @Override
    public void onPut(String sessionUuid, Session session) {
        String redisKey = WebSocketUidUtil.buildSessionUuidRedisKey(sessionUuid);
        String userId = Optional.ofNullable(session.getUserProperties())
                .map(mp -> mp.get(AbstractWebSocketEndpoint.WS_USER_ID_FLAG))
                .map(Object::toString)
                .orElse("0");
        stringRedisTemplate.opsForValue().set(
                redisKey,
                JSON.toJSONString(Map.of("time", DateTimeConverter.COMPACT_DATE_TIME.now(), "userId", userId)),
                // 过期时间（需要要比ws看门狗执行周期长）
                25, TimeUnit.HOURS
        );
    }
    
    @Override
    public void onRemove(String sessionUuid) {
        String redisKey = WebSocketUidUtil.buildSessionUuidRedisKey(sessionUuid);
        stringRedisTemplate.delete(redisKey);
    }
    
    /**
     * 看门狗 for 存在redis中ws唯一标识符，自动续期存活连接的ws唯一标识符、自动清除未存活连接的sw唯一标识符
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void websocketWatchdog() {
        log.info("websocketWatchdog start.");
        long now = System.currentTimeMillis();
        String traceXd = "traceXd";
        MDC.put(traceXd, "websocketWatchdog_" + now);
        try {
            Pair<Set<String>, Set<String>> pair = AbstractWebSocketEndpoint.aliveStatus();
            Set<String> aliveSessionUuidSet = pair.getLeft();
            Set<String> diedSessionUuidSet = pair.getRight();
            // 续期存活连接的ws唯一标识符
            if (!CollectionUtils.isEmpty(aliveSessionUuidSet)) {
                log.info("for redis key, to renewal websocket-session-uuid -> {}.", aliveSessionUuidSet);
                for (String sessionUuid : aliveSessionUuidSet) {
                    // 过期时间（需要要比ws看门狗执行周期长）
                    stringRedisTemplate.expire(WebSocketUidUtil.buildSessionUuidRedisKey(sessionUuid), 25, TimeUnit.HOURS);
                }
            }
            
            // 清除未存活连接的ws唯一标识符
            if (!CollectionUtils.isEmpty(diedSessionUuidSet)) {
                log.info("for redis key, to delete websocket-session-uuid -> {}.", diedSessionUuidSet);
                for (String sessionUuid : diedSessionUuidSet) {
                    AbstractWebSocketEndpoint.removeLocalSession(sessionUuid, this);
                }
            }
            log.info("websocketWatchdog end.");
        } catch (Exception e) {
            log.error("websocketWatchdog occur exception.", e);
        } finally {
            try {
                MDC.remove(traceXd);
            } catch (Exception ignore) {
            }
        }
    }
}